Ext.namespace('VAS');
/**
 * 快捷方式面板
 * 初始化参数：
 *  setting:Object 快捷方式设置的参数 可选，不设置不出现这部分，包括两个属性：
 *      image:String 图片
 *      handler:Function 响应函数，无参数
 *  list :Object 快捷方式列表的参数 可选，不设置不出现这部分，包括一个属性
 *      loadUrl:String 列表加载地址，加载后的数据格式为
 *          [{text:'',image:'',url:''}]
 *      handler: Function 点击快捷方式的响应函数，参数为url
 *  info Object 加载用户信息参数 可选，不设置不出现这部分，包括如下属性
 *      image:String 用户头像图片
 *      loadUrl:String 加载用户信息的地址
 *      tool:Array 按钮的数组，每个按钮包括：
 *          image:String 图片
 *          handler:Function 响应函数,无参数 
 */

VAS.ShortcutPanel=Ext.extend(Ext.Panel,{
	
	initComponent  : function() {
		var thisConfig = {
			id		: 'shortcutPanel',
		    border	:	false,
		    frame	:	false,
		    bodyStyle : 'background:#ECF3FB',
			autoScroll	:	true,
			tbar:[	
				'->',	
				'-',
				{
					xtype:"dynamicTbar"
					,text:'桌面设置'
					,eventType:'tbar'
					,icon:'lib/vas/img/menuIcon/advise16.png'
					,actionType : 'showShourCut'
				}
			]
		}
		
		Ext.apply(this, thisConfig);
		Ext.apply(this.initialConfig, thisConfig);
		Ext.ux.DynamicGridPanel.superclass.initComponent.apply(this, arguments);
	},
	
    onRender : function(ct, position){
        VAS.ShortcutPanel.superclass.onRender.call(this,ct,position);
        var dh=Ext.DomHelper;
        var ct=dh.append(this.body,'<div class="u-shortcut-panel"></div>');
        //增加一个div 让它在有文字折行时自动撑开u-shortcut-panel
        var last=dh.append(ct,'<div style="clear:both"></div>');
        //中间的快捷列表
        if(this.list){
	        Ext.Ajax.request({
	            url:this.list.loadUrl,
	            scope:this,
	            success:function(response){
	            	//检查session是否过期
					checkTimeOut(response);
	                var responseObj=Ext.decode(response.responseText);
	                if(responseObj.data && responseObj.data.length > 0) {
                        for(var i=0,l=responseObj.data.length;i<l;i++){
                            var e=responseObj.data[i];
                            if(!e.icon){//添加属性，否则下面的模版会报错
                                e.icon='';
                            }
                            if(e.tips == null){
                            	e.tips = '';
                            }
                        }
    	                this.list.data=responseObj.data;
                        this.list.defaultIcon=this.defaultIcon;
    			        var contentTpl = new Ext.XTemplate(
    			        	 '<div id="shortCuts" class="availableLot" >',
	    			        	'<tpl for="data">',
    			        			'<tpl if="icon">',
                                        '<div class="inline" onclick="shortCutLink(\'{url}\',\'{id}\',\'{topId}\')"><img src="{icon}" class="imgThumb" qtip="{tips}"/><input type="hidden" name="menuId" value="{id}"><br/><br/><br/><br/><br/>{text}</div>',
                                    '</tpl>',
                                    '<tpl if="!icon">',
                                        '<div class="inline" onclick="shortCutLink(\'{url}\',\'{id}\',\'{topId}\')"><img src="images/bk.gif" class="imgThumb" qtip="{tips}"/><input type="hidden" name="menuId" value="{id}"><br/><br/><br/><br/><br/>{text}</div>',
                                    '</tpl>',
	                            '</tpl>',
	                         '</div>'
                        );
    	                contentTpl.insertBefore(last,this.list);
    	                //计算div(shortCuts)的高度
    	                var height = document.body.clientHeight-219;
    	                document.getElementById('shortCuts').style.height = height;
    	                var carElements = Ext.get('shortCuts').select('div');
					    Ext.each(carElements.elements, function(el) {
					        var dd = new Ext.dd.DD(el, 'shortCutsDDGroup', {
					            isTarget  : false
					        });
					        Ext.apply(dd, overrides);
					    });
					    //Instantiate instances of Ext.dd.DDTarget for the cars and trucks container
					    var carsDDTarget    = new Ext.dd.DDTarget('shortCuts','shortCutsDDGroup');  
                    } 
	            }
	        });  
        };
        
        // A list of method overrides
	    var overrides = {
	        // Only called when element is dragged over the a dropzone with the same ddgroup
	        onDragEnter : function(evtObj, targetElId) {
	            // Colorize the drag target if the drag node's parent is not the same as the drop target
	            if (targetElId != this.el.dom.parentNode.id) {
	                this.el.addClass('dropOK');
	            }
	            else {
	                // Remove the invitation
	                this.onDragOut();
	            }
	        },
	        // Only called when element is dragged out of a dropzone with the same ddgroup
	        onDragOut : function(evtObj, targetElId) {
	            this.el.removeClass('dropOK');
	        },
	        //Called when mousedown for a specific amount of time
	        b4StartDrag : function() {
	            if (!this.el) {
	                this.el = Ext.get(this.getEl());
	            }
	            //this.el.highlight();
	            //Cache the original XY Coordinates of the element, we'll use this later.
	            this.originalXY = this.el.getXY();
	        },
	        // Called when element is dropped not anything other than a
	        // dropzone with the same ddgroup
	        onInvalidDrop : function() {
	            this.invalidDrop = true;
	
	        },
	        endDrag : function(data) {
	            if (this.invalidDrop === true) {
	                this.el.removeClass('dropOK');
	
	                var animCfgObj = {
	                    easing   : 'elasticOut',
	                    duration : 1,
	                    scope    : this,
	                    callback : function() {
	                        this.el.dom.style.position = '';
	                    }
	                };
	                this.el.moveTo(this.originalXY[0], this.originalXY[1], animCfgObj);
	                delete this.invalidDrop;
	                
	                //根据拖动后的顺序组装menuId字符串
	                var menuIds = '';
	                var carElements = Ext.get('shortCuts').select('div');
				    Ext.each(carElements.elements, function(el) {
				    	if(typeof el.children[1].value != 'undefined'){
				    		if(menuIds == ''){
				    			menuIds += el.children[1].value;
				    		}else{
				    			menuIds = menuIds + ',' + el.children[1].value;
				    		}
				    	}
				    });
				    //保存拖动后的顺序
				    Ext.Ajax.request({
				    	url : 'admin/system/ShortcutAction!saveShortcut.action',
				    	params : {menuIds:menuIds},
			            scope:this,
					   	success : function(response, options) {
					   	    //检查session是否过期
						    checkTimeOut(response);
					   		var responseObj = Ext.util.JSON.decode(response.responseText);
					   		if(!responseObj.success){
					   			alertFailure(responseObj);
					   		}
					   	},	
			            failure : function(response, options) {
							Ext.Msg.alert('提示','服务器异常！');
						}
				    });
	            }
	        },
	        // Called upon successful drop of an element on a DDTarget with the same
	        onDragDrop : function(evtObj, targetElId) {
	            // Wrap the drop target element with Ext.Element
	            var dropEl = Ext.get(targetElId);

	            // Perform the node move only if the drag element's parent is not the same as the drop target
//	            if (this.el.dom.parentNode.id != targetElId) {
	
	                // Move the element
	                dropEl.appendChild(this.el);
	
	                // Remove the drag invitation
	                this.onDragOut(evtObj, targetElId);
	
	                // Clear the styles
	                this.el.dom.style.position ='';
	                this.el.dom.style.top = '';
	                this.el.dom.style.left = '';
//	            }
//	            else {
//	                // This was an invalid drop, lets call onInvalidDrop to initiate a repair
//	                this.onInvalidDrop();
//	            }
	        }
	    };
    }
});
Ext.reg('shortcutpanel', VAS.ShortcutPanel);
